package com.ridu.project.beshid.service.impl;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;

@Service
public class RestService {

    public String postStringEntity(String url, String requestJson) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
        URI uri = UriComponentsBuilder.fromHttpUrl(url).build().encode().toUri();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(uri, entity, String.class);
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        } else {
            throw new Exception(responseEntity.getStatusCode().toString());
        }
    }

    public Object postForEntity(String url) {
        return postForEntity(url);
    }

    public Object postForEntity(String url, MultiValueMap<String, String> map) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate rest = new RestTemplate();
        URI uri = UriComponentsBuilder.fromHttpUrl(url).build().encode().toUri();
        ResponseEntity<String> responseEntity = rest.postForEntity(uri, request, String.class);
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        } else {
            throw new Exception(responseEntity.getStatusCode().toString());
        }
    }

    public Object getForObject(String uri, Map<String, String> map, Class c) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.queryParam(entry.getKey(), entry.getValue());
        }

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(builder.build().encode().toUri(), c);
    }

    public Object getForObject(String uri, Class c) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri);
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(builder.build().encode().toUri(), c);
    }
}
